/*
*/
var gReq = null;

function FunpHelper() {
    this._post = null;
}

FunpHelper.prototype = {
    load: function() {
	    var target = this;

		if (gBrowser.mPanelContainer) {
			var container = gBrowser.mPanelContainer;
			container.addEventListener("select", function(e){target.onTabSelect(e)}, false);
			container.addEventListener("DOMNodeInserted", function(e){target.onTabAdded(e)}, false);
		}

		gBrowser.addProgressListener(target.urlBarListener,
			Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);

		this.getFunpPushes(gBrowser.contentDocument.location.toString());
	},

    unload: function() {
		gBrowser.removeProgressListener(this.urlBarListener);
	},

    onTabAdded: function(e) {
		document.getElementById('firefunp-statusbar-pushes').value = '';
	},

    onTabSelect: function(e) {
		var browser = gBrowser.getBrowserAtIndex(gBrowser.mTabContainer.selectedIndex);
		this.getFunpPushes(browser.contentDocument.location.toString());
	},

    onPageLoad: function(e) {
		if (e.originalTarget instanceof HTMLDocument) {
		    var doc = e.originalTarget;
			if (doc.defaultView.frameElement) {
				return;
			}
			gFunpHelper.getFunpPushes(gBrowser.contentDocument.location.toString());
		}
	},

    onPageUnload: function(e) {
		var panel = document.getElementById('firefunp-statusbar-button');
		var label = document.getElementById('firefunp-statusbar-pushes');

		label.value = "Loading...";
		panel.onmouseover = function(e) {};
		panel.onmouseout = function(e) {};
		panel.onclick = function(e) {};
	},

    getFunpPushes: function(url) {
		var req_url = "http://funp.com/tools/buttoniframe.php?url=" + encodeURIComponent(url);

		if (gReq == null) gReq = new XMLHttpRequest();

		gReq.onload = this.updateButton;
		gReq.open("GET", req_url);
		gReq.send(null);
	},

    updateButton: function() {
		var res = gReq.responseText;
		var panel = document.getElementById('firefunp-statusbar-button');
		var elem = document.getElementById('firefunp-statusbar-pushes');
	    var a = res.match(/<span>([0-9]*)<\/span>/);
		
		if (a) {
		    elem.value = a[1];
		} else {
		    elem.value = '0';
        }
        
		var pressed = res.match(/class=".*pressed"/);
		if (!pressed) {
			panel.onmouseover = function(e) {
			    panel.style.cursor = 'pointer';
				panel.style.textDecoration = 'underline';
			};
			panel.onmouseout = function(e) {
				panel.style.cursor = '';
				panel.style.textDecoration = 'none';
			};

			if (a) { // 別人推過的
				var pid = res.match(/id="push_button_(.*)" class/)[1];
				var post = new XMLHttpRequest();
				gFunpHelper._post = post;
				post.onload = gFunpHelper.completePush;
				panel.onclick = function(e) { 
				    post.open("GET", "http://funp.com/push/push.ajax.php?tools=&pid="+pid);
				    post.setRequestHeader("REFERER", "http://funp.com/tools/buttoniframe.php");
				    post.setRequestHeader("HTTP_REFERER", "http://funp.com/tools/buttoniframe.php");
					post.send(null); 
				};
			} else {
				panel.onclick = function(e) {
				    var tab = gBrowser.addTab(res.match(/href="(http:\/\/funp.com\/push\/submit\/.*)"/)[1], null, null);
					gBrowser.selectedTab = tab;
				};
			}

		} else {
			panel.onmouseover = function(e) {};
			panel.onmouseout = function(e) {};
		    panel.onclick = function(e) {};
		}
	},

    completePush: function() {
		var req = gFunpHelper._post;
		var res = req.responseText;
		var panel = document.getElementById('firefunp-statusbar-button');
		var elem = document.getElementById('firefunp-statusbar-pushes');
		var rsobj = eval('('+res+')');
		if (rsobj.res == 'error' && rsobj.type == 'not_login') {
		    var tab = gBrowser.addTab("http://funp.com/push/push.ajax.php?pid="+pid+"&tools=", null, null);
			gBrowser.selectedTab = tab;
		} else if (rsobj.res == 'ok') {
			var pushes = parseInt(elem.value);
			elem.value = (pushes + 1);
			panel.onmouseover = function(e) {};
			panel.onmouseout = function(e) {};
			panel.onclick = function(e) {};
		}

	},

    urlBarListener: {
        QueryInterface: function(aIID) {
		    if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
				aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
				aIID.equals(Components.interfaces.nsISupports))
					return this;
			throw Components.results.NS_NOINTERFACE;
		},

        onLocationChange: function(aProgress, aRequest, aURI) {
			var panel = document.getElementById('firefunp-statusbar-button');
			var label = document.getElementById('firefunp-statusbar-pushes');

			label.value = "讀取中...";
			panel.onmouseover = function(e) {};
			panel.onmouseout = function(e) {};
			panel.onclick = function(e) {};
		},

        onStateChange: function() {},
	    onProgressChange: function() {},
		onStatusChange: function() {},
		onSecurityChange: function() {},
		onLinkIconAvailable: function() {}
	},

    simplePush: function() {
	    var page = gBrowser.contentDocument.location.toString();
		var url = "http://funp.com/push/submit/?url=" + encodeURIComponent(page);

		var tab = gBrowser.addTab(url, null, null);
		gBrowser.selectedTab = tab;
	}
};

var gFunpHelper = new FunpHelper();

window.addEventListener("load", function(e) { gFunpHelper.load(e); gBrowser.addEventListener('load', gFunpHelper.onPageLoad, true); }, false);
window.addEventListener("unload", function(e) { gFunpHelper.unload(e); /*gBrowser.addEventListener('unload', gFunpHelper.onPageUnload, true);*/ }, false);
